from ui.RCQ import Ui_MainWindow
from PySide6.QtWidgets import QApplication,QMainWindow,QMessageBox,QFileDialog,QTableWidgetItem,QListWidgetItem
from PySide6.QtCore import QDate,Qt
from PySide6 import QtWidgets,QtGui

from bs4 import BeautifulSoup

import sys,urllib.request,os,time



class MyWindow(Ui_MainWindow,QMainWindow):
    def __init__(self,parent=None):
        super(MyWindow,self).__init__(parent)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.pushButton_2.clicked.connect(self.msg)
        self.ui.pushButton.clicked.connect(self.getDatas)
        self.ui.listWidget.itemClicked.connect(self.itemClick)
        self.ui.tableWidget.itemClicked.connect(self.tableClick)
        
    def msg(self):
        try:
            self.dir_path=QFileDialog.getExistingDirectory(None,"选择路径",os.getcwd())
            self.ui.lineEdit.setText(self.dir_path)
        except Exception as e:
            print(e)
    # 从网页中提取数据
    def urlTosoup(self,url):
        response=urllib.request.urlopen(url)
        html=response.read()
        # 创建beautifulSoup对象它可以从html或xml文件中提取数据
        soup=BeautifulSoup(html,"html.parser")
        return soup
            
    def getData(self,url,path):
        soup=self.urlTosoup(url)
        link=soup.select('.booklist a')
        print(soup)
        path=path+'\\'+self.date+'\\'
        if not os.path.isdir(path):
            os.mkdir(path)
        for item in link:
            articleUrl=self.baseurl+item['href']
            articleSoup=self.urlToSoup(articleUrl)
            # 获取文章标题
            title=str(articleSoup.find("h1")).lstrip("<h1>").rstrip("</h1>")
            author=str(articleSoup.find(id="pub_date")).strip()  #获取作者
            filename=path+title+'.txt'  #设置文章保存路径
            content=articleSoup.select(".blkContainerSblkCon p")
            # with open as newFile:
            newFile=open(filename,"w")
            newFile.write("<<"+title+">>\n\n")   #向文章中写入标题和换行
            newFile.write(author+"\n\n")          #向文章中写入作者和换行
            for c in content:
                text=c.text
                newFile.write(text)
            newFile.close()
            QMessageBox.information(None,"提示",self.date+"的读者文章保存完成",QMessageBox.OK)
            
    # 获取所有文件
    def getFiles(self):
        # 列出文件夹下所有的目录与文件
        self.list=os.listdir(self.ui.lineEdit.text()+'/'+self.ui.lineEdit_2.text())
                
    def bindTable(self):
        for i in range(0,len(self.list)):  #遍历文件列表
            self.ui.tableWidget.insertRow(i)   #添加新行
            # 设置第一列的值为期数
            self.ui.tableWidget.setItem(i,0,QTableWidgetItem(self.ui.lineEdit_2.text()))
            # 第2列的值为文件名
            self.ui.tableWidget.setItem(i,1,QTableWidgetItem(self.list[i]))
    
    def bindList(self):
        for i in range(0,len(self.list)):  #遍历文件列表
            self.item=QListWidgetItem(self.ui.listWidget)   # 创建列表项
            self.item.setIcon(QtGui.QIcon('note.ico'))  # 设置列表项图标
            self.item.setText(str(self.list[i])[0:5]+'...')  #截取字符串，显示5个字符
            self.item.setToolTip(self.list[i])
            
            # 设置选中与否
            self.item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
            
    def getDatas(self):
        try:
            while True:
                self.date=self.ui.lineEdit_2.text()
                # 设置文章初始地址
                # self.baseurl='http://www.52duzhe.com/'+self.date.replace('-','_')+'/'
                self.baseurl='http://www.shuben.co/txt/426.html'+self.date.replace('-','_')+'/'
                print(self.baseurl)
                
                urlList=self.baseurl+'index.html'
                self.getData(urlList,self.ui.lineEdit.text())
        except Exception as e:
            print(e)
        self.getFiles()
        self.bindList()
        self.bindTable()
    # 表格单击方法，用来打开选中项
    def itemClick(self,item):
        os.startfile(self.ui.lineEdit.text()+'\\'+self.ui.lineEdit_2.text()+'\\'+item.toolTip())
        
    # 表格单击方法，用来打开选中项
    def tableClick(self,item):
        os.startfile(self.ui.lineEdit.text()+'\\'+self.ui.lineEdit_2.text()+'\\'+item.text())
        
        
    
            
    
        
            
            
    
        
        


if __name__=="__main__":
    app=QApplication(sys.argv)
    win=MyWindow()
    win.show()
    app.exec()